package com.example.player.util;

import android.util.Log;

import java.io.File;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * 本工具类为从网络上下载图片
 * @author 朱文权
 * */
public class Network {
    // 网易云音乐API常量
    private static final String SEARCH_API = "https://music.163.com/api/cloudsearch/pc";
    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36";

    /**
     * 下载歌曲封面
     * @param songName 歌曲名称
     * @param savePath 保存路径（需要包含文件名和扩展名）
     * @return 是否下载成功
     */
    public static boolean downloadCover(String songName, String savePath) {
        try {
            // 1. 发送搜索请求
            JSONObject searchResult = searchSong(songName);

            // 2. 解析歌曲信息
            JSONObject song = getFirstSong(searchResult);
            if (song == null) {
                Log.e("ERROR","未找到相关歌曲");
                return false;
            }

            // 3. 获取高清封面URL
            String coverUrl = buildHighQualityCoverUrl(song);

            // 4. 下载并保存封面
            return downloadAndSaveImage(coverUrl, savePath);
        } catch (Exception e) {
            Log.e("ERROR","发生错误: " + e.getMessage());
            return false;
        }
    }

    // 搜索歌曲
    private static JSONObject searchSong(String songName) {
        String url = SEARCH_API + "?s=" + songName + "&type=1&offset=0&limit=1";

        HttpResponse response = HttpRequest.get(url)
                .header("User-Agent", USER_AGENT)
                .header("Referer", "https://music.163.com/")
                .timeout(10000)
                .execute();

        if (response.getStatus() != 200) {
//            throw new RuntimeException("搜索请求失败，状态码：" + response.getStatus());
            Log.e("ERROR","搜索请求失败，状态码：" + response.getStatus());
        }

        return JSONUtil.parseObj(response.body());
    }

    // 获取第一首歌曲
    private static JSONObject getFirstSong(JSONObject searchResult) {
        JSONObject result = searchResult.getJSONObject("result");
        if (result == null || result.getInt("songCount", 0) == 0) {
            return null;
        }

        JSONArray songs = result.getJSONArray("songs");
        return songs.size() > 0 ? songs.getJSONObject(0) : null;
    }

    // 构造高清封面URL
    private static String buildHighQualityCoverUrl(JSONObject song) {
        String originUrl = song.getJSONObject("al").getStr("picUrl");
        // 将封面尺寸替换为 1000x1000
        return originUrl.replaceFirst("\\d{2,4}x\\d{2,4}(?=\\.jpg$)", "1000x1000");
    }

    // 下载并保存图片
    private static boolean downloadAndSaveImage(String url, String savePath) {
        HttpResponse response = HttpRequest.get(url)
                .header("Referer", "https://music.163.com/")
                .timeout(15000)
                .execute();

        if (response.isOk()) {
            FileUtil.writeFromStream(response.bodyStream(), new File(savePath));
            return true;
        }
        System.err.println("图片下载失败，状态码：" + response.getStatus());
        Log.e("ERROR","图片下载失败，状态码：" + response.getStatus());
        return false;
    }

}
